<?php
/**
 * 案件进度管理控制器
 */
namespace app\lawcase\controller;

use app\base\BaseController;
use app\lawcase\model\LawcaseProgress;
use app\lawcase\validate\LawcaseProgressCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use think\facade\Log;
use think\facade\Request;

class Progress extends BaseController
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new LawcaseProgress();
    }

    /**
     * 获取案件进度列表
     * @param array $where 查询条件
     * @param array $param 分页参数
     * @return array|\think\Paginator
     */
    public function getlist($where = [], $param = [])
    {
        try {
            $result = $this->model->getlist($where, $param);
            
            return to_assign(0, '获取成功', ['data' => $result]);
        } catch (\Exception $e) {
            Log::error('获取案件进度列表失败1：' . $e->getMessage());
            return to_assign(11, '获取失败：' . $e->getMessage(), ['data' => []]);
        }
    }

    /**
     * 添加案件进度
     * 若为 AJAX 请求，验证并保存进度信息；否则返回视图页面
     */
    public function add()
    {
        if (Request::isAjax()) {
            $param = get_params();

                if (empty($param['case_id']) || $param['case_id'] <= 0) {
                    return to_assign(1, '案件ID不能为空且必须大于0');
                }

                try {
                    validate(LawcaseProgressCheck::class)->check($param);
                } catch (\Exception $e) {
                    return to_assign(1, $e->getMessage());
                }
                
                $param['operator'] = $this->uid;
                $param['create_time'] = time();
                
                $this->model->addProgress($param);
        }else{
            $caseId = input('case_id/d', 0);
            return view('', ['case_id' => $caseId]);
        }
        
    }
    /**
     * 删除案件进度
     * 根据进度 ID 删除进度信息
     */
    public function delete()
    {
        $id = get_params("id");
        return json($this->model->removeProgress($id));
    }
    
    /**
     * 案件进度列表
     * 若为 AJAX 请求，根据参数查询进度列表并返回数据；否则返回视图页面
     */
    public function index()
    {
        if (Request::isAjax()) {
            $param = get_params();
            $caseId = !empty($param['case_id']) ? $param['case_id'] : input('case_id/d', 0);
            
            $where = [];
            if (!empty($caseId)) {
                $where['case_id'] = $caseId;
            }
            
            $searchParams = [
                'page' => input('page/d', 1),
                'limit' => input('limit/d', 15),
                'case_number' => $param['case_number'] ?? '',
                'event_type' => $param['event_type'] ?? '',
                'operator' => $param['operator'] ?? 0
            ];
            
            $result = $this->model->getlist($where, $searchParams);
            
            // 直接返回模型处理好的数据结构
            return json($result);
        }
        return view();
    }
}